import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartList: [],
    userInfo: null
  },
  mutations: {
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    addToCart(state, product) {
      const found = state.cartList.find(item => item.id === product.id)
      if (found) {
        found.quantity++
      } else {
        state.cartList.push({
          ...product,
          quantity: 1
        })
      }
    },
    updateCartItemQuantity(state, { id, quantity }) {
      const found = state.cartList.find(item => item.id === id)
      if (found) {
        found.quantity = quantity
      }
    },
    removeFromCart(state, id) {
      state.cartList = state.cartList.filter(item => item.id !== id)
    }
  },
  actions: {
    login({ commit }, userInfo) {
      return new Promise((resolve) => {
        commit('setUserInfo', userInfo)
        localStorage.setItem('token', userInfo.token)
        resolve()
      })
    },
    logout({ commit }) {
      commit('setUserInfo', null)
      localStorage.removeItem('token')
    }
  }
}) 